#include "QtUI/AddNewPackageCommand.qth"
#include "QtUI/AddNewPackageCommand.moh"
#include "QtUI/PackageInformationDialog.qth"
#include "QtUI/PackageInformationWidget.qth"
#include "QtUI/PackageUndoableCommands.qth"
#include "QtUI/QtUIConfigurationCenter.hpp"
#include "QtUI/QtUndoableCommand.hpp"
#include "Ctrl/ControlCenter.hpp"
#include "Ctrl/PackageController.hpp"
#include "Model/Package.hpp"
#include "Model/DuplicateNameError.hpp"
#include "Model/InvalidNameError.hpp"
#include <QtGui/QAction>
#include <QtGui/QUndoStack>
#include <QtGui/QMessageBox>

namespace QtUI
{

AddNewPackageCommand::AddNewPackageCommand( QAction* pBoundAction)
	: UICommandBase( pBoundAction)
	, Impl::ProjectRelatedCommandEnabler( pBoundAction)
{
}

// ---------------------------------------------------------------------------------------------------------------------

bool AddNewPackageCommand::execute( bool checked /*= false*/)
{
	Model::Package* pParentPackage = Ctrl::ControlCenter::instance().packageController().currentPackage();
	if( NULL == pParentPackage)
	{
		pParentPackage = &Ctrl::ControlCenter::instance().prjController().controlledProject().rootPackage();
	}

	PackageInformationDialog dlg;
	int result = result = dlg.exec();
	while( result == QDialog::Accepted)
	{
		try
		{
			std::string packageName = dlg.widget().packageName().toStdString();
			std::string packageDescription = dlg.widget().packageDescription().toStdString();
			std::auto_ptr< Model::Package> pNewPackage( new Model::Package( packageName, packageDescription));
			QtUI::QtUndoableCommand* pNewCommand 
				= QtUI::PackageUndoableCommands::createAddNewPackageCommand( Ctrl::ControlCenter::instance(), pParentPackage, pNewPackage.get());
			QtUI::QtUIConfigurationCenter::qtUIConfigCenter().undoStack()->push( pNewCommand);
			pNewPackage.release();
			break;
		}
		catch( Model::DuplicateNameError& )
		{
			QMessageBox::critical( 
				&dlg,
				tr( "Adding New Package", "Error message box title"),
				tr( "The name of the package is already in use.", "Error message for duplicate package name"));
		}
		catch( Model::InvalidNameError& e)
		{
			QMessageBox::critical(
				&dlg,
				tr( "Adding New Package", "Error message box title"),
				e.invalidName().empty() ? 
					tr( "The name of the package can't be empty.", "Error message for empty package name")
					:
					tr( "The name of the package is invalid.", "Error message for invalid package name"));
		}
		result = dlg.exec();
	}
	return result == QDialog::Accepted;
}

} // namespace QtUI
